package com.my.mygaode

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.amap.api.maps.model.LatLng
import com.my.mygaode.bean.BitmojiBean
import com.my.mygaode.bean.MarkerBean
import com.my.mygaode.databinding.FragmentMapBinding
import com.my.mygaode.view.MapContainerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @ClassName MapFragment
 * @Description TODO
 * @Author mwj
 * @Date 2023/7/18 14:53
 * @Version 1.0
 **/
class MapFragment : Fragment() {

    private var fragmentMapBinding: FragmentMapBinding? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        fragmentMapBinding = FragmentMapBinding.inflate(layoutInflater)
        return fragmentMapBinding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        fragmentMapBinding?.map?.onCreate(savedInstanceState)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initListener()
        var list = JsonParseUtil.getGsonList(
            "[{\"userId\":47,\"tengxunCode\":\"986494634\",\"nickName\":\"用户15123456701\",\"faceUrl\":\"http://8.134.38.20:8234/images/95390e72-a9a4-49ee-ad87-a4134bba5191.jpg\",\"latitude\":\"39.916296\",\"longitude\":\"116.410344\",\"mojiUpdatetime\":\"1689124947000\",\"mojiUrl\":\"https://img1.baidu.com/it/u=1601328011,3989558915&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=150\",\"backgroundUrl\":null}]",
            BitmojiBean.DataBean::class.java
        )
        list?.let {
            lifecycleScope.launch() {
                if (!it.isNullOrEmpty()) {
                    val markerList = ArrayList<MarkerBean>()
                    for (bean in it!!) {
                        val marker = withContext(Dispatchers.IO) {
                            addFriendsStatusMarkerToMap(bean)
                        }
                        if (marker != null) {
                            markerList.add(marker)
                        }
                    }
                    fragmentMapBinding?.map?.showListMarkers(markerList)
                }
            }
        }
    }

    private fun initListener() {
        fragmentMapBinding?.apply {
            map.setMapContainerViewBack(object : MapContainerView.MapContainerViewBack {
                override fun updateMap() {
                    updateLocation()
                }
            })
            locationState.setOnClickListener {
                map?.moveMySelfCamera()
            }
            logout.setOnClickListener {
                startActivity(Intent(requireActivity(), SettingsActivity::class.java))
            }
        }

    }

    private fun updateLocation() {
        var latitude = fragmentMapBinding?.map?.getLocationLatLng()?.latitude
        var longitude = fragmentMapBinding?.map?.getLocationLatLng()?.longitude
        Log.i("mygaode", "拿到经纬度---->" + latitude + "," + longitude)

        updateMyLocationMarkerView("https://img1.baidu.com/it/u=1601328011,3989558915&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=150")
    }

    /**
     * 更新自己位置信息Marker
     * @param url String
     */
    private fun updateMyLocationMarkerView(url: String?) {
        val view: View = layoutInflater.inflate(R.layout.ly_map_img, null)
        val imageView = view.findViewById<ImageView>(R.id.iv_img)
        val textView = view.findViewById<TextView>(R.id.tv_text)
        textView.text = "我"
        GlideUtils.getImageUrlToBitmap(requireContext(), url) { bitmap ->
            imageView.setImageBitmap(GlideUtils.getScaleToBitmap(bitmap, 80f.dp, 80f.dp))
            fragmentMapBinding?.map?.addMySelfMarkerBean(
                view, fragmentMapBinding?.map?.getLocationLatLng() ?: LatLng(
                    0.0,
                    0.0
                )
            )
            fragmentMapBinding?.map?.showMarkers()
        }

    }

    override fun onResume() {
        super.onResume()
        fragmentMapBinding?.map?.onResume()
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    override fun onPause() {
        super.onPause()
        fragmentMapBinding?.map?.onPause()
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        fragmentMapBinding?.map?.onSaveInstanceState(outState)
    }

    /**
     * 方法必须重写
     * map的生命周期方法
     */
    override fun onDestroy() {
        fragmentMapBinding?.map?.setMapContainerViewBack(null)
        fragmentMapBinding?.map?.onDestroy()
        super.onDestroy()
    }

    /**
     * 更新好友的状态信息显示
     * @param bitmojiBean DataBean?
     * @return MarkerBean?
     */
    private suspend fun addFriendsStatusMarkerToMap(bitmojiBean: BitmojiBean.DataBean?): MarkerBean? {
        if (bitmojiBean == null || TextUtils.isEmpty(bitmojiBean.userId)) return null
        var marker: MarkerBean? = null
        val view: View = layoutInflater.inflate(R.layout.ly_map_img, null)
        val imageView = view.findViewById<ImageView>(R.id.iv_img)
        val textView = view.findViewById<TextView>(R.id.tv_text)
        textView.text = bitmojiBean.nickName
//        LogUtils.d(LogUtils.TAG_DATA, "加载图片--->" + bitmojiBean?.mojiUrl)
        var bitmap: Bitmap? = null
        try {
            bitmap = GlideUtils.getImageBitmap(
                requireContext(),
                bitmojiBean?.mojiUrl
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
        imageView.setImageBitmap(GlideUtils.getScaleToBitmap(bitmap, 80f.dp, 80f.dp))
        marker = fragmentMapBinding?.map?.addMarkerBean(
            bitmojiBean?.userId ?: "",
            view,
            LatLng(bitmojiBean?.latitude ?: 0.0, bitmojiBean?.longitude ?: 0.0), false
        )
        return marker
    }
}